﻿using TrueSync;
using UnityEngine;

namespace HEFramework
{
    public static class SkillEffectRangeComponentSystem
    {
        [EntitySystem]
        public class SkillEffectRangeComponentAwakeSystem : AwakeSystem<SkillEffectRangeComponent>
        {
            protected override void Awake(SkillEffectRangeComponent _self)
            {
            }
        }


        /// <summary>
        /// 是否在影响范围内
        /// </summary>
        /// <param name="_self"></param>
        /// <param name="_id">技能效果ID</param>
        /// <param name="_a">触发点</param>
        /// <param name="_b">目标点</param>
        /// <param name="_dir">方向</param>
        /// <returns></returns>
        public static bool InEffectRange(this SkillEffectRangeComponent _self, int _id, TSVector _a, TSVector _b, TSVector _dir = default)
        {
            var dc = _self.GetSceneChild<DataTableComponent>();
            if (dc == null)
            {
                return false;
            }

            var table = dc.LoadDataTable<DRSkillEffect>();

            if (table == null)
            {
                return false;
            }

            var data = table.GetData(_id);

            switch (data.RangeType)
            {
                case (int)eSkillEffectRangeType.Circle:
                {
                    if (TSVector.Distance(_a, _b) <= Formula.LG(data.Radius))
                    {
                        return true;
                    }
                }
                    break;
                case (int)eSkillEffectRangeType.Cone:
                {
                    // 获取目标点到触发点的向量
                    var directionToTarget = _b - _a;
                    // 获取触发方向的向量（默认会返回一个单位向量，不应该为零向量）
                    var normalizedDir = _dir == default ? new TSVector(1, 0, 0) : _dir.normalized;
                    // 计算方向向量与目标向量的夹角
                    var angle = TSVector.Angle(normalizedDir, directionToTarget);
                    // 判断是否在角度范围内且距离小于等于给定的最大半径
                    if (angle <= data.Angle / 2 && TSVector.Distance(_a, _b) <= Formula.LG(data.Radius))
                    {
                        return true;
                    }
                }
                    break;
            }

            return false;
        }
    }
}